package tk.xboot.ws;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import tk.xboot.ws.conf.WsContextProvider;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/ws/{uid}",configurator = WsContextProvider.class)
public class WebSocketServer {

    private final Set<String> keys = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());

    private Object obj = new Object();

    @OnOpen
    public void onOpen(Session session, EndpointConfig config, @PathParam("uid") String uid) {
        synchronized (obj) {    // synchronized needed.
            log.info("UID:{}",uid);
            session.getOpenSessions().add(session);
            session.getUserProperties().put("uid", uid);
        }
        log.info("session is open, current online count:{}",session.getOpenSessions().size());
    }

    @OnMessage
    public void onMessage(Session session,String message){
        Set<String> keys = new HashSet<>();
        keys.add("a");
        keys.add("b");
        keys.add(message);
        synchronized (session) {
            session.getUserProperties().put("k", keys);
        }
        log.info("Get message from client: {}",message);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason){
        System.out.println(">>> closing the session now.");
        Set<String> set = (Set<String>)session.getUserProperties().get("k");
        set.forEach(o->{
            System.out.println(o);
        });
        synchronized (session) {
            session.getOpenSessions().remove(session);
        }
        log.info(session.getClass().getName());
        log.info("Close the web socket client:{}",session.getId());
    }

    @OnError
    public void onError(Session session, Throwable throwable){
        log.error("Error:{} , session id:{}, error",throwable.getMessage(),session.getId(),throwable);
    }



}
